<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateWechatUserAPIRequest;
use App\Http\Requests\API\UpdateWechatUserAPIRequest;
use App\Models\WechatUser;
use App\Repositories\WechatUserRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

/**
 * Class WechatUserController
 * @package App\Http\Controllers\API
 */

class WechatUserAPIController extends AppBaseController
{
    /** @var  WechatUserRepository */
    private $wechatUserRepository;

    public function __construct(WechatUserRepository $wechatUserRepo)
    {
        $this->wechatUserRepository = $wechatUserRepo;
    }

    /**
     * @param Request $request
     * @return Response
     *
     * @SWG\Get(
     *      path="/wechatUsers",
     *      summary="Get a listing of the WechatUsers.",
     *      tags={"WechatUser"},
     *      description="Get all WechatUsers",
     *      produces={"application/json"},
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  type="array",
     *                  @SWG\Items(ref="#/definitions/WechatUser")
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function index(Request $request)
    {
        $this->wechatUserRepository->pushCriteria(new RequestCriteria($request));
        $this->wechatUserRepository->pushCriteria(new LimitOffsetCriteria($request));
        $wechatUsers = $this->wechatUserRepository->all();

        return $this->sendResponse($wechatUsers->toArray(), trans('flash.api.retrieve_success', ['model' => 'Wechat Users']));
    }

    /**
     * @param CreateWechatUserAPIRequest $request
     * @return Response
     *
     * @SWG\Post(
     *      path="/wechatUsers",
     *      summary="Store a newly created WechatUser in storage",
     *      tags={"WechatUser"},
     *      description="Store WechatUser",
     *      produces={"application/json"},
     *      @SWG\Parameter(
     *          name="body",
     *          in="body",
     *          description="WechatUser that should be stored",
     *          required=false,
     *          @SWG\Schema(ref="#/definitions/WechatUser")
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  ref="#/definitions/WechatUser"
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function store(CreateWechatUserAPIRequest $request)
    {
        $input = $request->all();

        $wechatUsers = $this->wechatUserRepository->create($input);

        return $this->sendResponse($wechatUsers->toArray(), trans('flash.api.save_success', ['model' => 'Wechat User']));
    }

    /**
     * @param int $id
     * @return Response
     *
     * @SWG\Get(
     *      path="/wechatUsers/{id}",
     *      summary="Display the specified WechatUser",
     *      tags={"WechatUser"},
     *      description="Get WechatUser",
     *      produces={"application/json"},
     *      @SWG\Parameter(
     *          name="id",
     *          description="id of WechatUser",
     *          type="integer",
     *          required=true,
     *          in="path"
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  ref="#/definitions/WechatUser"
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function show($id)
    {
        /** @var WechatUser $wechatUser */
        $wechatUser = $this->wechatUserRepository->findWithoutFail($id);

        if (empty($wechatUser)) {
            return $this->sendError(trans('flash.api.not_found', ['model'=>'Wechat User']), 404);
        }

        return $this->sendResponse($wechatUser->toArray(), trans('flash.api.retrieve_success', ['model' => 'Wechat User']));
    }

    /**
     * @param int $id
     * @param UpdateWechatUserAPIRequest $request
     * @return Response
     *
     * @SWG\Put(
     *      path="/wechatUsers/{id}",
     *      summary="Update the specified WechatUser in storage",
     *      tags={"WechatUser"},
     *      description="Update WechatUser",
     *      produces={"application/json"},
     *      @SWG\Parameter(
     *          name="id",
     *          description="id of WechatUser",
     *          type="integer",
     *          required=true,
     *          in="path"
     *      ),
     *      @SWG\Parameter(
     *          name="body",
     *          in="body",
     *          description="WechatUser that should be updated",
     *          required=false,
     *          @SWG\Schema(ref="#/definitions/WechatUser")
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  ref="#/definitions/WechatUser"
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function update($id, UpdateWechatUserAPIRequest $request)
    {
        try {
            $session = $this->checkWeachtMiniProgramLogin($request);
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }

        if ($GLOBALS['wx_user_session']['wechat_user_id'] != $id)
        {
            return $this->sendError('不能编辑其他人资料', 403);
        }

        $input = $request->all();
        if (isset($input['phone']) && ! validatePhone($input['phone']))
        {
            $error = [
                'message' => 'The given data was invalid.',
                'errors' => [
                    'phone' => ['手机号码格式有误!']
                ]
            ];
            return Response::make($error, 422);
        }

        /** @var WechatUser $wechatUser */
        $wechatUser = $this->wechatUserRepository->findWithoutFail($id);
        if (empty($wechatUser)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Wechat User']), 404);
        }

        if (isset($input['headimgurl']) && fileUrlExists($input['headimgurl']))
        {
            $input['headimgurl'] = fileUrl($input['headimgurl']);
        }

        if (isset($input['openid']))
        {
            unset($input['openid']);
        }

        if (isset($input['unionid']))
        {
            unset($input['unionid']);
        }

        $wechatUser = $this->wechatUserRepository->update($input, $id);
        if ($wechatUser)
        {
            unset($wechatUser->openid);
            unset($wechatUser->unionid);
        }

        return $this->sendResponse($wechatUser->toArray(), trans('flash.api.update_success', ['model' => 'WechatUser']));
    }

    /**
     * @param int $id
     * @return Response
     *
     * @SWG\Delete(
     *      path="/wechatUsers/{id}",
     *      summary="Remove the specified WechatUser from storage",
     *      tags={"WechatUser"},
     *      description="Delete WechatUser",
     *      produces={"application/json"},
     *      @SWG\Parameter(
     *          name="id",
     *          description="id of WechatUser",
     *          type="integer",
     *          required=true,
     *          in="path"
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  type="string"
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function destroy($id)
    {
        /** @var WechatUser $wechatUser */
        $wechatUser = $this->wechatUserRepository->findWithoutFail($id);

        if (empty($wechatUser)) {
            return $this->sendError('Wechat User not found', 404);
        }

        $wechatUser->delete();

        return $this->sendResponse($id, trans('flash.api.delete_success', ['model' => 'Wechat User']));
    }
}
